/**
 * Author(s): xuming.Wong <xuming.Wong@gmail.com>
 */
#include "DiagramEdge.h"
#include "DiagramNode.h"

namespace QSThink
{
	static const double Pi = 3.14159265358979323846264338327950288419717;
	static double TwoPi = 2.0 * Pi;

	DiagramEdge::DiagramEdge( DiagramNode *sourceNode, DiagramNode *destNode )
		: _arrowSize(0)
	{

		setAcceptedMouseButtons(0);
		_source=sourceNode;
		_dest=destNode;
		_source->addEdge(this);
		_dest->addEdge(this);
		adjust();

		setZValue(-1);


	}


	DiagramEdge::~DiagramEdge()
	{
		//deleted by node so 

	}


	DiagramNode* DiagramEdge::sourceNode() const
	{
		return _source;

	}

	DiagramNode* DiagramEdge::destNode() const
	{
		return _dest;
	}

	void DiagramEdge::adjust()
	{
		if (!_source||!_dest){
			return;
		}
		QLineF line(mapFromItem(_source,0,0),mapFromItem(_dest,0,0));
		qreal len=line.length();
		prepareGeometryChange();
		
			_sourcePoint=line.p1();
			_destPoint=line.p2();

	
		

	}

	void DiagramEdge::setSourceNode( DiagramNode *node )
	{
		_source = node;
		adjust();

	}

	void DiagramEdge::setDestNode( DiagramNode *node )
	{
		_dest = node;
		adjust();


	}

	QRectF DiagramEdge::boundingRect() const
	{
		if(!_source||!_dest){
			return QRectF();
		}
		qreal penWidth=1;
		qreal extra=(penWidth+_arrowSize)/2.0f;
		qreal width=_destPoint.x()-_sourcePoint.x();
		qreal height=_destPoint.y()-_sourcePoint.y();
		QRectF rect(_sourcePoint,QSizeF(width,height));
		return rect.normalized().adjusted(-extra,-extra,extra,extra);


	}

	void DiagramEdge::paint( QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget )
	{
		//return;
		if(!_source||!_dest){
			return;
		}
		QLineF line(_sourcePoint, _destPoint);
		if (qFuzzyCompare(line.length(), qreal(0.))){
			return;
		}
		// Draw the line itself
		painter->setPen(QPen(Qt::black, 0.6));
		painter->drawLine(line);

		return;
	}

}
